package com.sita.tboard.hitchhike.publish;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.model.LatLng;
import com.github.jjobes.slidedatetimepicker.SlideDateTimeListener;
import com.github.jjobes.slidedatetimepicker.SlideDateTimePicker;
import com.sita.bike.R;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.support.LocationController;
import com.sita.tboard.hitchhike.HitchhikeActivity;
import com.sita.tboard.hitchhike.HitchhikeConstants;
import com.sita.tboard.hitchhike.HitchhikeContentActivity;
import com.sita.tboard.hitchhike.bean.SelectedAddress;
import com.sita.tboard.hitchhike.bean.TicketModel;
import com.sita.tboard.hitchhike.bean.TicketStatus;
import com.sita.tboard.hitchhike.detail.PassengerTripDetailActivity;
import com.sita.tboard.hitchhike.helper.HitchhikeNetworkHelper;
import com.sita.tboard.hitchhike.listeners.OnHitchhikeCreateTripLanListener;
import com.sita.tboard.hitchhike.search.PoiKeywordSearchActivity;
import com.sita.tboard.hitchhike.search.PoiSearchResultContainer;
import com.sita.tboard.util.DateUtils;
import com.sita.tboard.util.TextUtils;

import java.util.Date;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.ToastUtils;

public class PassengerPublishTripActivity extends HitchhikeContentActivity implements LocationSource, AMapLocationListener {

    private SelectedAddress fromAddress;
    private SelectedAddress toAddress;
    private long departureTime;
    private boolean isStartLocating;
    private LocationSource.OnLocationChangedListener mListener;
    private Date planDate;

    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.start_address)
    TextView startAddressView;
    @Bind(R.id.end_address)
    TextView endAddressView;
    @Bind(R.id.departure_time)
    TextView departureTimeView;

    public PassengerPublishTripActivity() {
        // Required empty public constructor
    }

    public static Intent newIntent() {
        Intent intent = new Intent(GlobalContext.getGlobalContext(), PassengerPublishTripActivity.class);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hitchhike_passenger_publish_trip);
        ButterKnife.bind(this);

        customizeToolbar(mToolbar, R.string.publish_trip_plan);

        AMapLocation aMapLocation = LocationController.getLastKnownLocation();
        fromAddress = new SelectedAddress().setLongitude(aMapLocation.getLongitude())
                .setLatitude(aMapLocation.getLatitude()).setCity(aMapLocation.getCity())
                .setProvince(aMapLocation.getProvince())
                .setFullAddress(aMapLocation.getDistrict() + aMapLocation.getStreet()
                        + aMapLocation.getAoiName());
        startAddressView.setText(fromAddress.getFullAddress());

        departureTime = System.currentTimeMillis() + HitchhikeConstants.DEFAULT_FUTURE_TIME;
        planDate = new Date(departureTime);
        departureTimeView.setText(DateUtils.formatDateTime(planDate));
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onResume() {
        super.onResume();

        toAddress = toAddress == null ? new SelectedAddress() : toAddress;
        fromAddress = fromAddress == null ? new SelectedAddress() : fromAddress;

        SelectedAddress mapFromAddress = PoiSearchResultContainer.getInstance().getResult(true);
        if (mapFromAddress != null) {
            fromAddress = mapFromAddress;
            startAddressView.setText(fromAddress.getFullAddress());
        }

        SelectedAddress mapToAddress = PoiSearchResultContainer.getInstance().getResult(false);
        if (mapToAddress != null) {
            toAddress = mapToAddress;
            endAddressView.setText(toAddress.getFullAddress());
        }

    }

    @OnClick(R.id.btn_send)
    void onClickBtnSend() {
        if (fromAddress != null && !fromAddress.isEmpty() && toAddress != null && !toAddress.isEmpty()) {
            if (departureTime <= 0) {
                departureTimeView.setError(getString(R.string.please_type_departure_time));
                return;
            }

            HitchhikeNetworkHelper.INSTANCE.passengerCreateTrip(fromAddress, toAddress, departureTime, new OnHitchhikeCreateTripLanListener() {
                @Override
                public void onSuccess(TicketModel ticket) {
                    ToastUtils.show(GlobalContext.getGlobalContext(), R.string.shunfengche_planed);
                    startActivity(PassengerTripDetailActivity.newIntent(ticket));
                    finish();
                }

                @Override
                public void onFailure(Throwable throwable) {
                    ToastUtils.show(GlobalContext.getGlobalContext(), TextUtils.getThrowableMessage(throwable));
                }
            });
        }
    }

    @OnClick(R.id.from_line)
    void onClickFromLine() {
        Intent intent = PoiKeywordSearchActivity.newIntent(true);
        startActivity(intent);
    }

    @OnClick(R.id.to_line)
    void onClickToLine() {
        Intent intent = PoiKeywordSearchActivity.newIntent(false);
        startActivity(intent);
    }

    @OnClick(R.id.departure_time)
    void onClickDepartureTime() {
        new SlideDateTimePicker.Builder(getSupportFragmentManager())
                .setListener(new SlideDateTimeListener() {
                    @Override
                    public void onDateTimeSet(Date date) {
                        departureTime = date.getTime();
                        departureTimeView.setText(DateUtils.formatDateTime(date));
                    }
                })
                .setInitialDate(planDate)
                //.setMinDate(minDate)
                //.setMaxDate(maxDate)
                .setIs24HourTime(true)
                //.setTheme(SlideDateTimePicker.HOLO_DARK)
                //.setIndicatorColor(Color.parseColor("#990000"))
                .build()
                .show();
    }

    @Override
    public void activate(LocationSource.OnLocationChangedListener listener) {
        mListener = listener;
        if (!isStartLocating) {
            LocationController.startTracking(this);
            isStartLocating = true;
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        LocationController.stopTracking(this);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null) {
            mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
        }
        //判断定位是否成功
        if (aMapLocation == null || aMapLocation.getErrorCode() != 0) {
            return;
        }
        //地点的纬度，在-90 与90 之间的double 型数值
        double latitude = aMapLocation.getLatitude();
        //地点的经度，在-180 与180 之间的double 型数值
        double longitude = aMapLocation.getLongitude();
        //角标显示的位置
        LatLng latLng = new LatLng(latitude, longitude);

        //设置相关数据
        fromAddress.setLatitude(latitude)
                .setLongitude(longitude)
                .setCity(aMapLocation.getCity())
                .setProvince(aMapLocation.getProvince())
                .setFullAddress(aMapLocation.getDistrict() + aMapLocation.getStreet()
                        + aMapLocation.getAoiName());

        startAddressView.setText(fromAddress.getFullAddress());
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home: {
                finish();
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
